package utils;

import android.view.View;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import dagger.Module;

/**
 * 类似于 RadioButtonGroup
 * Created by jiangwj on 2014/10/10.
 */
@Module
public class ViewSelectGroup implements View.OnClickListener {

    private List<View> views = new ArrayList<View>();

    private int selectedIndex = -1;

    private View selectedView = null;

    private OnSelectChangeListener listener = null;

    @Inject
    public ViewSelectGroup() {
    }

    public void addView(View view) {
        if (views.contains(view)) {
            return;
        }
        //
        views.add(view);
        //
        view.setOnClickListener(this);
    }

    public void removeView(View view) {
        if (views.remove(view) && view.hasOnClickListeners()) {
            view.setOnClickListener(null);
        }
    }

    public int getViewCount() {
        return views.size();
    }


    public View getSelectedView() {
        return selectedView;
    }

    public void setSelectedView(View v) {
        int idx = -1;
        if (v != null) {
            idx = views.indexOf(v);
        }
        if (idx < 0) {
            selectedIndex = -1;
            selectedView = null;
        } else {
            selectedIndex = idx;
            selectedView = v;
        }
        //
        checkViewsSelection();
        //
        fireListener();
    }


    public int getSelectedIndex() {
        return selectedIndex;
    }

    public void setSelectedIndex(int index) {
        if (index < 0 || index >= views.size()) {
            selectedIndex = -1;
            selectedView = null;
        } else {
            selectedIndex = index;
            selectedView = views.get(index);
        }
        //
        checkViewsSelection();
        //
        fireListener();
    }


    //
    protected void checkViewsSelection() {
        for (View v : views) {
            v.setSelected(v == selectedView);
        }
    }


    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        int idx = views.indexOf(v);
        if (idx < 0) {
            v.setOnClickListener(null);
            selectedView = null;
            return;
        }
        //
        selectedIndex = idx;
        selectedView = v;
        //
        checkViewsSelection();
        //
        fireListener();
    }



    public void setListener(OnSelectChangeListener l) {
        listener = l;
    }

    public boolean hasListener() {
        return listener != null;
    }

    protected void fireListener() {
        if (listener != null) {
            listener.onViewSelectChanged(selectedView, selectedIndex);
        }
    }

    public static interface OnSelectChangeListener {
        void onViewSelectChanged(View v, int position);
    }

}
